﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ODS.Resources;
using System.Diagnostics;
using System.Windows.Media;
using ODS.Utils;
using ODS.ViewModel;


namespace ODS
{
    public partial class MainPage : PhoneApplicationPage
    {     

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            //For scroll bottom menu
            MaxTranformY = (int)slidingMenu.Height - slidingMenu.GetHeightTopBar() ;
  
        }

        bool isNeedReload = false;

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            App.mainPage = this;

            CheckShowAndHiddenViews();

            if (isNeedReload)
            {
                showWaiting();

                await App.MainViewModel.LoadListDeviceFromUser();

                HiddenWaiting();
            }

            MainLongListSelector.DataContext = App.MainViewModel.DeviceViewModelList;
            MainLongListSelector.SelectedItem = null;

            AnimationUtil.getInstance().OnAnimationCompleted += MainPage_OnAnimationCompleted;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            isNeedReload = true;

            scrollDownSlidingMenu();
            slidingMenu.HiddenImageSelected();

            AnimationUtil.getInstance().OnAnimationCompleted -= MainPage_OnAnimationCompleted;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (!isMenuDowning)
            {
                scrollDownSlidingMenuWithAnimation();
            }
            e.Cancel = true;
            base.OnBackKeyPress(e);
        }

        private void MainLongListSelector_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (MainLongListSelector.SelectedItem == null)
                return;
            DeviceViewModel itemClicked = (DeviceViewModel)MainLongListSelector.SelectedItem;

            App.currentDeviceModel = itemClicked.DeviceModel;

            if (itemClicked.DeviceModel.IsActivatedSubscription)
            {
                this.NavigationService.Navigate(new Uri("/DetailDevicePage.xaml?DeviceID=" + itemClicked.DeviceModel.DeviceIMEI, UriKind.Relative));
            }
            else
            {
                this.NavigationService.Navigate(new Uri("/ActivatingDevice.xaml?DeviceID=" + itemClicked.DeviceModel.DeviceIMEI, UriKind.Relative));
            }
   
        }

        void showWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Visible;
        }

        void HiddenWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Collapsed;
        }

        void CheckShowAndHiddenViews()
        {
            if (App.MainViewModel.DeviceViewModelList.Count > 0)
            {
                MainLongListSelector.Visibility = Visibility.Visible;
                NoDeviceView.Visibility = Visibility.Collapsed;
            }
            else
            {
                MainLongListSelector.Visibility = Visibility.Collapsed;
                NoDeviceView.Visibility = Visibility.Visible;
            }
        }

        #region handle scroll bottom menu
        void MainPage_OnAnimationCompleted(bool isScrollDown)
        {
            if (isScrollDown)
            {
                MainLongListSelector.IsEnabled = true;
            }
            else
            {
                MainLongListSelector.IsEnabled = false;
            }
        }

        private void scrollDownSlidingMenu()
        {
            isMenuDowning = true;
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            transform.Y = 0;

            MainLongListSelector.IsEnabled = true;
        }

        private void scrollDownSlidingMenuWithAnimation()
        {
            isMenuDowning = true;
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            int Y = (int)transform.Y;
            AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
        }

        

        private const int LIMIT_SCROLL = 100;
        bool isMenuDowning = true;
        int MaxTranformY = 0;
        private bool checkIsTapOnTopOfSlidingMenu(Point point)
        {
            GeneralTransform gt=((UIElement)slidingMenu).TransformToVisual(this);
            Point pointOdSlidingMenu = gt.Transform(new Point(0,0));

            if (point.Y >= pointOdSlidingMenu.Y && point.Y <= pointOdSlidingMenu.Y + slidingMenu.GetHeightTopBar())
                return true;
            return false;
        }

        Point Point_Start;
        Point point_Move;
        int offset = 0;

        bool IsMouseEnterOnTopBar = false;

        private void LayoutRoot_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
			Debug.WriteLine("LayoutRoot_MouseEnter");

            Point_Start = e.GetPosition((UIElement)sender);
            point_Move = Point_Start;

            if (checkIsTapOnTopOfSlidingMenu(Point_Start))
            {
                IsMouseEnterOnTopBar = true;

                MainLongListSelector.IsEnabled = false;
                if (!isMenuDowning)
                {
                    Debug.WriteLine("UnRegisterEventMouseForGrids");
                    slidingMenu.UnRegisterEventMouseForGrids();
                }
                

            }
            else
                IsMouseEnterOnTopBar = false;
        }

        private void LayoutRoot_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (isTap)
            {
                isTap = false;
                return;
            }

            if (!IsMouseEnterOnTopBar)
                return;

            if (slidingMenu.IsUnRegisterEventMouseForGrids)
            {
                Debug.WriteLine("RegisterEventMouseForGrids");
                slidingMenu.RegisterEventMouseForGrids();
            }

        	Debug.WriteLine("LayoutRoot_MouseLeave");
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            int Y = (int)transform.Y;

            if (transform.Y < -(MaxTranformY - LIMIT_SCROLL))
            {

                AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                isMenuDowning = false;

            }
            else if (transform.Y > - LIMIT_SCROLL)
            {

                AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                isMenuDowning = true;

            }
            else
            {
                if (offset > 0)
                {
                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                    isMenuDowning = true;

                }
                else
                {
                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                    isMenuDowning = false;

                }
            }
        }

        private void LayoutRoot_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_MouseMove");

            if (!IsMouseEnterOnTopBar)
                return;

            var transform = slidingMenu.RenderTransform as TranslateTransform;

            point_Move = e.GetPosition((UIElement)sender);

            offset = (int)(point_Move.Y - Point_Start.Y);

            Point_Start = point_Move;

            Debug.WriteLine("offset: " + offset);

            if ((transform.Y <= -MaxTranformY && offset < 0))
            {
                isMenuDowning = false;

                MainLongListSelector.IsEnabled = false;
                return;
            }

            if ((transform.Y >= 0 && offset > 0))
            {
                isMenuDowning = true;

                MainLongListSelector.IsEnabled = true;
                return;
            }

            transform.Y += offset;

            if (transform.Y < -MaxTranformY)
                transform.Y = -MaxTranformY;
            if (transform.Y > 0)
                transform.Y = 0;

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                
                 slidingMenu.UpdateLayout();
            });
            

            Debug.WriteLine("MouseMove: " + point_Move);
        }

        bool isTap = false;

        private void LayoutRoot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_Tap");
            isTap = true;

            Point Point_click = e.GetPosition((UIElement)sender);

            if (checkIsTapOnTopOfSlidingMenu(Point_click))
            {
                var transform = slidingMenu.RenderTransform as TranslateTransform;
                int Y = (int)transform.Y;

                MainLongListSelector.IsEnabled = false;

                if (isMenuDowning)
                {

                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                    isMenuDowning = false;
                }
                else
                {
                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                    isMenuDowning = true;
                }
            }

            if (slidingMenu.IsUnRegisterEventMouseForGrids)
            {
                Debug.WriteLine("RegisterEventMouseForGrids");
                slidingMenu.RegisterEventMouseForGrids();
            }
        }

        #endregion


    }
}